<template>
	<el-dialog v-model="dialogVisible" append-to-body :show-close="false" :close-on-click-modal="false"
		class="flex-align" style="width: 100%;height: 100%;padding: 30px 24px;margin: 0;background: transparent;">
		<template #header>
			<el-card style="width: 100%;height: 100%;" body-style="padding: 0;" shadow="never">
				<template #header>
					<div class="flex-space-between">
						<div>
							<el-text style="font-size: 16px;">
								客户对账明细
							</el-text>
						</div>
						<div>
							<el-button @click="closeDialog">取消</el-button>
							<!-- <el-button @click="closeDialog">
								保存并继续创建
								<el-icon style="margin-left: 4px;">
									<ArrowDown />
								</el-icon>
							</el-button> -->
							<el-button type="primary" @click="submitForm(vFormRef)">
								保存
							</el-button>
						</div>
					</div>
				</template>
				<el-scrollbar ref="scrollbarRef" @scroll="handleScroll"
					:style="`height: calc(100vh - 69px - ( 30px + 30px));`">
					<el-form :model="formData" :rules="rules" ref="vFormRef" label-position="top" label-width="50px"
						style="padding: 16px;">
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="客户对账单" prop="customerStatement">
									<el-select @clear="selectClear('customerStatement')"
										v-model="formData.customerStatement"
										@change="(value:any)=>selectChange(value,'customerStatement')" multiple
										ref="customerStatement" clearable>
										<el-option v-for="item in customerStatementOption" :key="key"
											:label="item?.label" :value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div class="flex-align-center">
												<el-icon
													:color="customerStatementOption[customerStatementIndex]?.color">
													<component
														:is="customerStatementOption[customerStatementIndex]?.icon">
													</component>
												</el-icon>
												<!--  -->
												<el-text size="small"
													style="margin-left: 6px;">{{customerStatementOption[customerStatementIndex]?.label}}</el-text>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="发生日期" prop="occurrenceDate">
									<el-date-picker placeholder="请选择" style="width:100%;"
										v-model="formData.occurrenceDate" type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="12">
								<el-form-item label="产品" prop="product">
									<el-select @clear="selectClear('product')" v-model="formData.product"
										@change="(value:any)=>selectChange(value,'product')" multiple ref="product"
										clearable>
										<el-option v-for="item in productOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="productOption[productIndex]?.color">
															<component :is="productOption[productIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{productOption[productIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="类型" prop="salesOrder">
									<el-select @clear="selectClear('salesOrder')" v-model="formData.salesOrder"
										@change="(value:any)=>selectChange(value,'salesOrder')" multiple
										ref="salesOrder" clearable>
										<el-option v-for="item in salesOrderOption" :key="key" :label="item?.label"
											:value="item?.value">
											<!--  -->
											<div class="flex-align-center">
												<el-icon :color="item?.color">
													<component :is="item?.icon"></component>
												</el-icon>
												<!--  -->
												<el-text style="margin-left: 6px;">{{item?.label}}</el-text>
											</div>
										</el-option>
										<!--  -->
										<template #tag>
											<div style="padding-left: 6px;">
												<div>
													<div class="flex-align-center">
														<el-icon :color="salesOrderOption[salesOrderIndex]?.color">
															<component :is="salesOrderOption[salesOrderIndex]?.icon">
															</component>
														</el-icon>
														<!--  -->
														<el-text size="small"
															style="margin-left: 6px;">{{salesOrderOption[salesOrderIndex]?.label}}</el-text>
													</div>
												</div>
											</div>
										</template>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="16">
							<el-col :span="8">
								<el-form-item label="本次对账总额" prop="totalAmount">
									<el-input type="text" placeholder="自动计算结果" disabled v-model="formData.totalAmount"
										clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="已收款总额" prop="receivedAmount">
									<el-input type="text" placeholder="自动计算结果" disabled
										v-model="formData.receivedAmount" clearable></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="待收款总额" prop="pendingAmount">
									<el-input type="text" placeholder="自动计算结果" disabled v-model="formData.pendingAmount"
										clearable></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
				<!--  -->
			</el-card>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { useRoute, useRouter } from 'vue-router';
	import request from '../../../utils/request';
	import { List, UploadFilled, UserFilled, WalletFilled, CirclePlus, DocumentAdd, Delete, Refresh, GoodsFilled, Grid } from '@element-plus/icons-vue';
	import { mergeObjects, formatNumber, findIndexByLabel } from '../../../utils';
	import { useSelect } from '../../../utils/mixins';
	import { ElMessage, FormInstance } from 'element-plus';
	import { formatDate } from '../../../utils/date';
	const emits = defineEmits(['update']);
	const { handSelectChange } = useSelect();
	const router = useRouter();
	const route = useRoute();
	const vFormRef = ref(null);
	const loading = ref(false);

	// 表单
	const formData = ref({
		customerStatementId: null,//客户对账单
		customerStatement: [],
		occurrenceDate: null,//发生日期
		productId: null,// 产品
		product: [],
		salesOrderId: null,//类型
		salesOrder: [],
		totalAmount: null,//本次对账总额
		receivedAmount: null,//已收款总额
		pendingAmount: null,//待收款总额
	});
	//验证
	const rules = reactive({
		customerStatement: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//客户对账单
		occurrenceDate: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//发生日期
		product: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],// 产品
		salesOrder: [{ required: true, message: '不能为空！', trigger: ['blur', 'change'] }],//类型
		totalAmount: [],//本次对账总额
		receivedAmount: [],//已收款总额
		pendingAmount: [],//待收款总额
	});
	const pageData = ref({
		pageNum: 1,
		pageSize: 1000,
		total: 0,
		pages: 0,
	});
	// 客户对账单
	const customerStatementOption = ref([]);
	const customerStatementIndex = ref(-1);
	const customerStatement = ref(null);
	// 产品
	const productOption = ref([]);
	const productIndex = ref(-1);
	const product = ref(null);
	//类型
	const salesOrderOption = ref([]);
	const salesOrderIndex = ref(-1);
	const salesOrder = ref(null);
	//
	const dialogVisible = ref(false);
	/**
	 * 打开弹出层
	 */
	const openDialog = () => {
		dialogVisible.value = true;
		setTimeout(async () => {
			const result = await getPageId();
			//
			if (result) {
				getCustomerStatementList();
			}
		}, 10);
	}
	/**
	 * 关闭弹出层
	 */
	const closeDialog = () => {
		dialogVisible.value = false;
		vFormRef.value.resetFields();
		//清空url参数
		router.push({ query: {} });
	}
	//获取当前页面的数据
	const getPageId = async () => {
		if (!route.query.id) {
			return true;
		}
		//
		const result = await request({
			url: '/SalesReceipt/selectCustomerStatementDetailId',
			params: {
				customerStatementDetailId: route.query.id
			},
		});
		//
		console.log('getPageId --->', result);
		//
		formData.value = { ...result.data.t };
		//
		return true;
	}

	//改变
	const selectChange = (value : Array<any>, type : string, key : number) => {
		//所有下拉框的配置列表
		const typeList = [{
			type: 'customerStatement', //哪一个下拉框，根据ref
			option: customerStatementOption, //下拉列表选项
			indexVar: customerStatementIndex, //当前选中项
			idVar: 'customerStatementId', //当前id值
			blurRef: customerStatement, //ref
		}, {
			type: 'product', //哪一个下拉框，根据ref
			option: productOption, //下拉列表选项
			indexVar: productIndex, //当前选中项
			idVar: 'productId', //当前id值
			blurRef: product, //ref
		}, {
			type: 'salesOrder', //哪一个下拉框，根据ref
			option: salesOrderOption, //下拉列表选项
			indexVar: salesOrderIndex, //当前选中项
			idVar: 'salesOrderId', //当前id值
			blurRef: salesOrder, //ref
		}];
		//
		handSelectChange(formData, typeList, value, type, key);
		//
		if (type === 'customerStatement') {
			const index = findIndexByLabel(customerStatementOption.value, value[0], 'value');
			getSaleCustomerId(customerStatementOption.value[index].customerId);
		}
		//
	}
	//获取客户对账单
	const getCustomerStatementList = async () => {
		const result = await request({
			url: '/SalesReceipt/selectCustomerStatement',
			params: pageData.value,
		});
		//
		console.log('getCustomerStatementList --->', result);
		customerStatementOption.value = [];
		result.data.t.list.forEach((item : any, key : number) => {
			customerStatementOption.value.push({
				label: `${item.billNumber}`,
				value: item.customerStatementId,
				icon: Refresh,
				color: '#42b382',
				customerId: item.customerId
			});
			if (formData.value.customerStatementId === item.customerStatementId) {
				formData.value.customerStatement = [item.customerStatementId];
				customerStatementIndex.value = key;
				//
				getSaleCustomerId(item.customerId);
			}
		});
	}
	//根据客户id查询
	const getSaleCustomerId = async (customerId : number) => {
		const result = await request({
			url: '/SalesReceipt/selectSaleCustomerId',
			params: { customerId }
		});
		//
		console.log('getSaleCustomerId --->', result);
		//
		productOption.value = [];
		salesOrderOption.value = [];
		result.data.t.forEach(async (item : any, key : number) => {
			//产品
			productOption.value.push({
				label: `${item.product.productName}${item.product.model} | 在库${item.product.currentInventory}件`,
				value: item.product.productId,
				icon: UploadFilled,
				color: '#5283ff'
			});
			if (formData.value.productId === item.productId) {
				formData.value.product = [item.productId];
				productIndex.value = key;
			}
			//类型
			salesOrderOption.value.push({
				label: `${item.dictData[1].dictLabel}_${formatDate(item.occurrenceDate)}`,
				value: item.receivablePayableDetailId,
				icon: List,
				color: '#5283ff'
			});
			if (formData.value.salesOrderId === item.receivablePayableDetailId) {
				formData.value.salesOrder = [item.receivablePayableDetailId];
				salesOrderIndex.value = key;
			}
		});
	}
	//提交表单
	const submitForm = async (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		await formEl.validate(async (valid, fields) => {
			if (valid) {
				console.log('submitForm ---> ', formData.value);
				const data = { ...formData.value };
				delete data.customerStatement;
				delete data.product;
				let type = '';
				if (!route.query.id) {
					type = '/saveCustomerStatementDetail';
				} else {
					type = '/updateCustomerStatementDetail';
				}
				//
				const result = await request({
					url: '/SalesReceipt' + type,
					data: data,
					method: 'post'
				});
				//
				console.log('submitForm--->', result);
				//
				if (result.data.code === 200) {
					ElMessage.success({
						message: '操作成功！'
					});
				} else {
					ElMessage.error({
						message: result.data.msg
					});
				}
				//
				setTimeout(() => {
					closeDialog();
					emits('update');
				}, 1);
			} else {
				//
				console.log('error submit!', fields);
			}
		});
	}
	defineExpose({
		openDialog
	});
</script>
<style>
	@import '../../../assets/css/my-form-item.css';

	.form-item-bg {
		background-color: #bfdfff;
	}

	.form-item-bg1 {
		background-color: #a5f2e5;
	}

	.my.el-input .el-input__inner {
		opacity: 0;
	}

	/*  */
	.avatar-uploader {
		width: 178px;
		height: 178px;
	}

	.avatar-uploader .avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-uploader .el-upload {
		width: 100%;
		height: 100%;
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}

	.el-scrollbar__view {
		display: block !important;
	}

	/*  */
</style>

<style scoped lang="scss">
	@import '../../../assets/css/index.scss';
</style>